﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Orange.Mvc4App.Models;

namespace Orange.Mvc4App.Services {

    public interface IRackService : IBaseService<Rack> {
        string GetPath(string id);
        string GetRerackid(string rackid);
        Rack GetNext(string id);
    }

    public class RackService : BaseService, IRackService {
        public IList<Rack> GetList(Func<Rack, bool> filters) {
            if (filters != null)
                return db.Racks.Where(filters).ToList();
            else
                return db.Racks.ToList();
        }

        public Rack Find(params object[] keys) {
            return db.Racks.Find(keys);
        }

        public void Add(Rack model) {
            db.Racks.Add(model);
        }

        public void Update(Rack model) {
            db.Entry(model).State = EntityState.Modified;
        }

        public void Delete(Rack model) {
            foreach (var item in db.Racks
                .Where(r => r.Rerackid == model.Rackid)) {
                db.Racks.Remove(item);
            }
            db.Racks.Remove(model);
        }

        public void Save() {
            db.SaveChanges();
        }

        public void Dispose() {
            db.Dispose();
        }

        public Rack GetNext(string rerackid) {
            string id = string.Empty;
            if (!string.IsNullOrEmpty(rerackid)) {
                int tmp = 0;
                if (int.TryParse(
                        db.Racks.Where(r => r.Rerackid == rerackid)
                                .Max(c => c.Rackid), out tmp)) {
                    id = tmp.ToString();
                } else {
                    id = rerackid + "0001";
                }
            }
            return new Rack { Rackid = id, Rerackid = rerackid };
        }

        public string GetPath(string rackid) {
            var rack = db.Racks.Find(rackid);
            if (rack != null) {
                return GetPath(rack.Rerackid) + "," + rackid;
            }
            return "";
        }

        public string GetRerackid(string rackid) {
            return db.Racks.Find(rackid).Rerackid;
        }
    }
}